package com.jiyun.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiyun.pojo.Dept;
import com.jiyun.pojo.Emp;
import com.jiyun.pojo.EmpDTO;
import com.jiyun.pojo.EmpExcel;
import com.jiyun.service.EmpService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@RestController // controller的标记，spring容器，自动读取
@RequestMapping("emp") // 窄化路径
public class EmpController {

    @Autowired// DI：注入，将spring容器中的对象，注入当前的对象中
            EmpService empService;

    @RequestMapping("findPage")
    public Page findPage(Integer pageNum, Integer pageSize, @RequestBody EmpDTO empDTO) {
        return empService.findPage(pageNum, pageSize, empDTO);
    }

    @RequestMapping("deptList")
    public List<Dept> deptList() {
        return empService.deptList();
    }

    @RequestMapping("add")
    public void add(@RequestBody Emp emp) {
        empService.add(emp);
    }

    @RequestMapping("update")
    public void update(@RequestBody Emp emp) {
        empService.update(emp);
    }

    @RequestMapping("findById")
    public Emp findById(Integer id) {
        return empService.findById(id);
    }

    @RequestMapping("deleteOne")
    public void deleteOne(Integer id) {
        empService.deleteOne(id);
    }

    @RequestMapping("deleteAll")
    public void deleteAll(@RequestBody List<Emp> list) {
        for (Emp emp : list) {
            empService.deleteOne(emp.getId());
        }
    }

    @RequestMapping("exportExcel")
    public void exportExcel(HttpServletResponse response) throws IOException {
        List<Emp> list = empService.findAll();
        List<EmpExcel> empExcelList = new ArrayList<>();
        for (Emp emp : list) {
            EmpExcel empExcel = new EmpExcel();
            BeanUtils.copyProperties(emp, empExcel);
            empExcel.setEmpBirthday(emp.getBirthday().toString());
            empExcel.setDname(emp.getDept() == null ? "" : emp.getDept().getName());
            empExcelList.add(empExcel);
        }

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("员工信息", "UTF-8").replaceAll("/+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        // esayExcel进行导出
        // 将excel写入到哪个输出流中
        EasyExcel.write(response.getOutputStream())
                // excel的头信息在哪
                .head(EmpExcel.class)
                // excel的版本
                .excelType(ExcelTypeEnum.XLSX)
                // 表格的名字
                .sheet("员工列表")
                // 具体的数据
                .doWrite(empExcelList);

        //XSSFWorkbook workbook = new XSSFWorkbook();
        //XSSFSheet sheet = workbook.createSheet();
        //// 标题行的内容
        //XSSFRow title = sheet.createRow(0);
        //title.createCell(0).setCellValue("ID");
        //title.createCell(1).setCellValue("name");
        //title.createCell(2).setCellValue("sex");
        //title.createCell(3).setCellValue("hobby");
        //title.createCell(4).setCellValue("birthday");
        //title.createCell(5).setCellValue("dept");
        //
        //for (int i = 0; i < list.size(); i++) {
        //    Emp emp = list.get(i);
        //    XSSFRow row = sheet.createRow(i+1);
        //    row.createCell(0).setCellValue(emp.getId());
        //    row.createCell(1).setCellValue(emp.getName());
        //    row.createCell(2).setCellValue(emp.getSex());
        //    row.createCell(3).setCellValue(emp.getHobby());
        //    row.createCell(4).setCellValue(emp.getBirthday().toString());
        //    row.createCell(5).setCellValue(emp.getDept()==null?"":emp.getDept().getName());
        //}
        //
        //String fileName = "员工";
        //response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        //response.setCharacterEncoding("utf-8");
        //response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        //// 将文件，上传到前台
        //workbook.write(response.getOutputStream());
    }

    @RequestMapping("uploadExcel")
    public String uploadExcel(MultipartFile file) throws IOException {
        // 1.导入的文件的输入流对象
        // 2.具体的导入的对象
        // 3.导入的监听器，可以监听每一行的数据

        EasyExcel.read(file.getInputStream(), EmpExcel.class, new ReadListener<EmpExcel>() {
            // 每读取完一条数据，自动调用
            @Override
            public void invoke(EmpExcel o, AnalysisContext analysisContext) {

                // 将数据一条一条的插入到数据库中
                Emp emp = new Emp();
                BeanUtils.copyProperties(o, emp);
                emp.setId(null);// id必须由数据库自己生成
                emp.setBirthday(LocalDate.parse(o.getEmpBirthday()));
                Dept dept = empService.findByName(o.getDname());
                if (dept != null) {
                    emp.setDeptId(dept.getId());
                }

                empService.add(emp);

            }

            // 当所有的数据都读取完之后，调用
            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                System.out.println("数据以读取完毕");
                // 插入到数据库中
            }
        }).sheet().doRead();


        //XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
        //XSSFSheet sheet = workbook.getSheetAt(0);
        //int lastRowNum = sheet.getLastRowNum();
        //List<Emp> list = new ArrayList<>();
        //for (int i = 0; i < lastRowNum; i++) {
        //    XSSFRow row = sheet.getRow(i + 1);
        //    Emp emp = new Emp();
        //    double id = row.getCell(0).getNumericCellValue();
        //    String name = row.getCell(1).getStringCellValue();
        //    emp.setName(name);
        //    String sex = row.getCell(2).getStringCellValue();
        //    emp.setSex(sex);
        //    String hobby = row.getCell(3).getStringCellValue();
        //    emp.setHobby(hobby);
        //    String birthday = row.getCell(4).getStringCellValue();
        //    emp.setBirthday(LocalDate.parse(birthday));
        //    String dname = row.getCell(5).getStringCellValue();
        //    Dept dept = empService.findByName(dname);
        //    if(dept!=null) {
        //        emp.setDeptId(dept.getId());
        //    }
        //    list.add(emp);
        //}
        //
        //// 将解析出来的list实体类集合，放入数据库中
        //empService.addAll(list);
        return "导入成功！";
    }

}
